package com.bookstore.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bookstore.Domain.User;
import com.bookstore.mapper.UserMapper;
import com.bookstore.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 未来
 */
@Service
public class UserServiceImpl implements UserService {
    /**
     * alibaba标砖注入
     */
    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public List<User> getUsers() {
        List<User> users = userMapper.selectList(null);
        return users;
    }
    @Override
    public User findByName(String user_number) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_number",user_number);
        // 查询一个数据，出现多个结果使用List
        User user = userMapper.selectOne(wrapper);
        return user;
    }

    @Override
    public boolean saveUser(User user) {
        return userMapper.insert(user) > 0;
    }

    @Override
    public boolean updateUser(User user) {
        return userMapper.updateById(user) > 0;
    }

    /**
     * 根据账号删除
     * @param user_number ：根据用户id删除
     * @return
     */
    @Override
    public boolean deleteUser(String user_number) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_number",user_number);
        return userMapper.delete(wrapper)>0;
    }

    /**
     *  pages.getRecords():返回的是用户List集合
     * @param page ：页数
     * @param number ：一页显示多少条数据
     * @return
     */
    @Override
    public List<User> getPages(int page, int number) { ;
        Page<User> pages = new Page<>(page,number);
        IPage<User> userIPage = userMapper.selectPage(pages, null);
        return userIPage.getRecords();
    }

    /**
     * 通过id集合删除多个行数据
     * @param ids
     * @return
     */
    @Override
    public boolean deleteArr(int[] ids) {
        List<Integer> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        return userMapper.deleteBatchIds(idList)>0;
    }

    @Override
    public List<User> searchUsers(String query) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 设置模糊查询条件
        queryWrapper.like("user_number",query);
        return userMapper.selectList(queryWrapper);
    }


}
